#!/bin/bash
#########################################################
#                                                       #
#            pistar-remote Service Handler              #
#                                                       #
# Written for Pi-Star (http://www.mw0mwz.co.uk/pi-star) #
#               By Andy Taylor (MW0MWZ)                 #
#                                                       #
#                     Version 1.2                       #
#                                                       #
#########################################################

# Service Config
DAEMON=python
DAEMON_PATH=/usr/bin/
DAEMON_OPTS=/usr/local/sbin/pistar-remote
PGREP=/usr/bin/pgrep
KILL=/bin/kill
SLEEP=/bin/sleep

# Pre-flight checks...
test -x ${DAEMON_PATH}${DAEMON} || exit 0
test -x ${DAEMON_OPTS} || exit 0

# Check the remote app is enabled.
if grep "enabled" /etc/pistar-remote | grep -q "false" ; then
	exit 0;
fi

case "$1" in
	start)
		if [ `${PGREP} -f "${DAEMON_PATH}${DAEMON} ${DAEMON_OPTS}"` ]; then
			echo -e "pistar-remote is already running as PID "`${PGREP} -f "${DAEMON_PATH}${DAEMON} ${DAEMON_OPTS}"`
			exit 0;
		else
			${DAEMON_PATH}${DAEMON} ${DAEMON_OPTS} &
			echo -e "pistar-remote started as PID "`${PGREP} -f "${DAEMON_PATH}${DAEMON} ${DAEMON_OPTS}"`
			exit 0;
		fi
		;;

	stop)
		if [ `${PGREP} -f "${DAEMON_PATH}${DAEMON} ${DAEMON_OPTS}"` ]; then
			echo -e "Killing pistar-remote PID "`${PGREP} -f "${DAEMON_PATH}${DAEMON} ${DAEMON_OPTS}"`
			$KILL `${PGREP} -f "${DAEMON_PATH}${DAEMON} ${DAEMON_OPTS}"`
			exit 0;
		else
			echo -e "pistar-remote is not running"
			exit 0;
		fi
		;;

	restart)
		if [ `${PGREP} -f "${DAEMON_PATH}${DAEMON} ${DAEMON_OPTS}"` ]; then
			echo -e "Killing pistar-remote PID "`${PGREP} -f "${DAEMON_PATH}${DAEMON} ${DAEMON_OPTS}"`
			$KILL `${PGREP} -f "${DAEMON_PATH}${DAEMON} ${DAEMON_OPTS}"`
			$SLEEP 3
			${DAEMON_PATH}${DAEMON} ${DAEMON_OPTS} &
			echo -e "pistar-remote re-started as PID "`${PGREP} -f "${DAEMON_PATH}${DAEMON} ${DAEMON_OPTS}"`
			exit 0;
		else
			echo -e "pistar-remote is not running"
			${DAEMON_PATH}${DAEMON} ${DAEMON_OPTS} &
			echo -e "pistar-remote is started as PID "`${PGREP} -f "${DAEMON_PATH}${DAEMON} ${DAEMON_OPTS}"`
			exit 0;
		fi
		;;

	status)
		if [ `${PGREP} -f "${DAEMON_PATH}${DAEMON} ${DAEMON_OPTS}"` ]; then
			echo -e "pistar-remote is running as PID "`${PGREP} -f "${DAEMON_PATH}${DAEMON} ${DAEMON_OPTS}"`
		else
			echo -e "pistar-remote is not running"
		fi
		;;

	*)
		echo $"Usage: $0 {start|stop|restart|status}"
		exit 0
esac
